package com.examination.client.util;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Security;

public class AES {

    /*
     * 添加签名，验签，加密算法提供者
     */
    private static void addProvider(){
//        if (Security.getProvider("BC") == null) {
//            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
//        } else {
//            Security.removeProvider("BC"); //解决eclipse调试时tomcat自动重新加载时，BC存在不明原因异常的问题。
//            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
//        }

    }

    static{
        addProvider();
    }

    /*public static void main(String[] args) {
        try {
            addProvider();
            System.out.println(decrypt(
                    Base64.decodeBase64("Q6VDk\\/FWqmwfGPDLJfMHsA=="),
                    Base64.decodeBase64("VQiMIGRpgjD9blsBvp/0bg==")
                    , Base64.decodeBase64("rZ/9cMvZhbdxInwU4WprFY8TJja2wqFmZvZ9nqL6BIN9MPk/Uehsvo9y1rj3GZqNZ8O8pbupohINXMtKBM2Kb5gkCEBbzn2oUhFE67BvWRxqe1OaKj5Yv4FsYa7Gp4Pl4ulsWWvhqrAr8Z60IYIP9ZqPl4yrgFc4eJxrQJ3PUtRVGOnBdmJeVHI3Uz1G8o8j7QetY3voonl4R/1WLm9kJQ==")));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }*/

    public static String decrypt(byte[] key, byte[] iv, byte[] encData) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, generateIV(iv));
        //解析解密后的字符串
        return new String(cipher.doFinal(encData));
    }

    // 生成iv
    public static AlgorithmParameters generateIV(byte[] iv) throws Exception {
        AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
        params.init(new IvParameterSpec(iv));
        return params;
    }


}
